﻿using System;
using System.Data;
using System.Web.UI;
using BLL;
using ET;
using Ext.Net;
using HTML;
using Roles;

namespace ERP.Modules
{
    public partial class Room : UserControl
    {
        private readonly Room_BLL clsRoom = new Room_BLL();
        private readonly Warehouse_BLL _clsWarehouse = new Warehouse_BLL();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest)
            {
                CheckPermisstion();
                GetWarehouse();
                GetData();
                btnEdit.Disable(true);
                btnDel.Disable(true);
                btnExport.Disable(true);
                WindowsUnit();
                WindowsBranch();
                WindowsWarehouse();
            }
        }

        //-------Store-Datasource-----------------
        protected void StoreRoom_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            txtSearch.Text = string.Empty;
            SelectBoxRoomWarehouse.Text = string.Empty;
            GetData();
            GetWarehouse();
        }

        //--------Buttom-Main------------------------
        protected void btnAddNew_Click(object sender, DirectEventArgs e)
        {
            GetComboBox();
            ClearTextBox();
            WindowsRoom.Show();
        }

        protected void btnEdit_Click(object sender, DirectEventArgs e)
        {
            var sm = grRoom.GetSelectionModel() as CheckboxSelectionModel;
            foreach (SelectedRow row in sm.SelectedRows)
            {
                GetComboBox();
                ClearTextBox();
                DataDetail(int.Parse(row.RecordID));
                WindowsRoom.Show();
                sm.UpdateSelection();
            }
        }

        protected void btnDel_Click(object sender, DirectEventArgs e)
        {
            var sm = grRoom.GetSelectionModel() as CheckboxSelectionModel;
            foreach (SelectedRow row in sm.SelectedRows)
            {
                try
                {
                    Room_BLL.DeleteRoom(int.Parse(row.RecordID));
                }
                catch (Exception)
                {
                    clsFormat.Alert_ERROR("Thông Báo",
                        "Tồn tại tài liệu con, không xoá được vui lòng xoá tài liệu con trước !");
                }
            }
            GetData();
        }

        protected void SelectBoxRoomWarehouse_Change(object sender, DirectEventArgs e)
        {
            GetData();
        }
        //--------Buttom-Popup------------------------
        protected void btnSavePopUp_Click(object sender, DirectEventArgs e)
        {
            if (txtRoom_ID.Text == string.Empty)
            {
                InsertRoom();
            }
            else
            {
                if (CheckPermisstionDobclick())
                {
                    HTML.clsFormat.Alert_ERROR("Thông Báo", "Bạn không được cấp quyền để sửa đổi !");
                }
                else
                {
                    UpdateRoom();
                }    
            }
        }

        protected void btnCancelPopUp_Click(object sender, DirectEventArgs e)
        {
            WindowsRoom.Close();
        }

        //----------Click-------------------
        protected void RoomDblClick(object sender, DirectEventArgs e)
        {
            GetComboBox();
            ClearTextBox();
            int Room_Id = int.Parse(e.ExtraParams["Room_Id"]);
            DataDetail(Room_Id);
            WindowsRoom.Show();
        }

        #region[Method]

        protected void GetData()
        {
            if (SelectBoxRoomWarehouse.Text == string.Empty)
            {
                DataTable dtRoom = clsRoom.Search(txtSearch.Text);
                if (dtRoom != null && dtRoom.Rows.Count > 0)
                {
                    StoreRoom.DataSource = dtRoom;
                    StoreRoom.DataBind();
                }
                else
                {
                    grRoom.GetStore().RemoveAll();
                }
            }
            else
            {
                DataTable dtRoom = clsRoom.GetRoomFillter(int.Parse(SelectBoxRoomWarehouse.SelectedItem.Value));
                if (dtRoom != null && dtRoom.Rows.Count > 0)
                {
                    StoreRoom.DataSource = dtRoom;
                    StoreRoom.DataBind();
                }
                else
                {
                    grRoom.GetStore().RemoveAll();
                }
            }
        }

        protected void DataDetail(int id)
        {
            DataTable dtRoom = clsRoom.GetRoomDetail_Edit(id);
            if (dtRoom != null && dtRoom.Rows.Count > 0)
            {
                txtRoom_ID.Text = dtRoom.Rows[0]["Room_ID"].ToString();
                txtRoom_Alias.Text = dtRoom.Rows[0]["Room_Alias"].ToString();
                txtRoom_Name.Text = dtRoom.Rows[0]["Room_Name"].ToString();
                txtRoom_Tankage.Text = dtRoom.Rows[0]["Room_Tankage"].ToString();
                cbUnit.SetValue(int.Parse(dtRoom.Rows[0]["Unit_Id"].ToString()));
                cbWareHouse.SetValue(int.Parse(dtRoom.Rows[0]["Warehouse_Id"].ToString()));
                txtRoom_Note.Text = dtRoom.Rows[0]["Room_Note"].ToString();
            }
        }

        protected bool CheckInsert()
        {
            bool kiemtra = false;
            var clsRoom = new Room_BLL();
            DataTable dtRoom = clsRoom.GetRoom(string.Empty);
            if (dtRoom != null && dtRoom.Rows.Count > 0)
            {
                foreach (DataRow dr in dtRoom.Rows)
                {
                    if (txtRoom_ID.Text != dr["Room_ID"].ToString())
                    {
                        if (txtRoom_Alias.Text == dr["Room_Alias"].ToString())
                        {
                            kiemtra = true;
                            clsFormat.Alert_ERROR("Thông Báo", "Mã phòng chứa đã tồn tại !");
                        }
                        else if (txtRoom_Name.Text == dr["Room_Name"].ToString())
                        {
                            kiemtra = true;
                            clsFormat.Alert_ERROR("Thông Báo", "Tên phòng chứa đã tồn tại !");
                        }
                    }
                }
            }
            return kiemtra;
        }

        protected void InsertRoom()
        {
            try
            {
                if (!CheckInsert())
                {
                    var obj = new Room_ET
                    {
                        Room_Alias = txtRoom_Alias.Text,
                        Room_Name = txtRoom_Name.Text,
                        Room_Tankage = float.Parse(txtRoom_Tankage.Text),
                        Unit_Id = int.Parse(cbUnit.SelectedItem.Value),
                        Warehouse_Id = int.Parse(cbWareHouse.SelectedItem.Value),
                        Room_Note = txtRoom_Note.Text
                    };
                    Room_BLL.InsertRoom(obj);
                    clsFormat.Alert_INFO("Thông Báo", "Thêm mới thành công !");
                    GetData();
                    GetComboBox();
                    ClearTextBox();
                }
            }
            catch (Exception ex)
            {
                clsFormat.Alert_ERROR("Lỗi", ex.ToString());
            }
        }

        protected void UpdateRoom()
        {
            try
            {
                if (!CheckInsert())
                {
                    var obj = new Room_ET
                    {
                        Room_Id = int.Parse(txtRoom_ID.Text),
                        Room_Alias = txtRoom_Alias.Text,
                        Room_Name = txtRoom_Name.Text,
                        Room_Tankage = float.Parse(txtRoom_Tankage.Text),
                        Unit_Id = int.Parse(cbUnit.SelectedItem.Value),
                        Warehouse_Id = int.Parse(cbWareHouse.SelectedItem.Value),
                        Room_Note = txtRoom_Note.Text
                    };
                    Room_BLL.UpdateRoom(obj);
                    WindowsRoom.Close();
                    clsFormat.Alert_INFO("Thông Báo", "Sữa thành công!");
                    GetData();
                }
            }
            catch (Exception ex)
            {
                clsFormat.Alert_ERROR("Lỗi", ex.ToString());
            }
        }

        private void GetWarehouse()
        {
            var _dtWarehouse = _clsWarehouse.GetWarehouse();
            if (_dtWarehouse != null && _dtWarehouse.Rows.Count > 0)
            {
                StoreRoomWarehouse.DataSource = _dtWarehouse;
                StoreRoomWarehouse.DataBind();
            }
            else
            {
                SelectBoxRoomWarehouse.GetStore().RemoveAll();
            }
        }
        #endregion

        #region [ComboBox]

        protected void GetComboBox()
        {
            var clsUnit = new Unit_BLL();
            DataTable dtUnit = clsUnit.Search(string.Empty);
            if (dtUnit != null && dtUnit.Rows.Count > 0)
            {
                UnitStore.DataSource = dtUnit;
                UnitStore.DataBind();
            }

            var clsBranch = new Branch_BLL();
            DataTable dtBranch = clsBranch.Search(string.Empty);
            if (dtBranch != null && dtBranch.Rows.Count > 0)
            {
                BranchStore.DataSource = dtBranch;
                BranchStore.DataBind();
            }

            var clsWarehouse = new Warehouse_BLL();
            DataTable dtWarehouse = clsWarehouse.Search(string.Empty);
            if (dtWarehouse != null && dtWarehouse.Rows.Count > 0)
            {
                WarehouseStore.DataSource = dtWarehouse;
                WarehouseStore.DataBind();
            }
        }

        protected void BranchSelectIndex_Change(object sender, StoreReadDataEventArgs e)
        {
            cbWareHouse.ReadOnly = false;
            var clsKho = new Warehouse_BLL();
            if (cbBranch.SelectedItem.Value != null)
            {
                DataTable dtKho = clsKho.GetWarehouseBranch(int.Parse(cbBranch.SelectedItem.Value));
                if (dtKho != null && dtKho.Rows.Count > 0)
                {
                    WarehouseStore.DataSource = dtKho;
                    WarehouseStore.DataBind();
                }
                else
                {
                    cbBranch.Clear();
                    cbWareHouse.ReadOnly = true;
                    clsFormat.Alert_INFO("Thông báo", "Chi nhánh này không có kho vui lòng chọn chi nhánh khác !");
                }
            }
            else
            {
                cbBranch.Clear();
                cbWareHouse.ReadOnly = true;
                clsFormat.Alert_INFO("Thông báo", "Vui lòng chọn chi nhánh !");
            }
        }

        protected void ReloadComboBox(object sender, StoreReadDataEventArgs e)
        {
            GetComboBox();
        }

        #endregion

        #region[ClearTextbox]

        protected void ClearTextBox()
        {
            FormPanelRoom.Reset();
            txtRoom_ID.Text = string.Empty;
            txtRoom_Alias.Text = MaTuDong();
            txtRoom_Name.Text = string.Empty;
            txtRoom_Tankage.Text = "0";
            txtRoom_Note.Text = string.Empty;

            cbUnit.Clear();
            cbBranch.Clear();
            cbWareHouse.Clear();
            cbWareHouse.ReadOnly = true;
        }

        #endregion

        #region[MaTangTuDong]

        protected string MaTuDong()
        {
            int i;
            DataTable dt = clsRoom.Search(string.Empty);
            if (dt != null && dt.Rows.Count > 0)
            {
                int max = int.Parse(dt.Rows[0]["Room_ID"].ToString());
                for (i = 0; i < dt.Rows.Count; i++)
                {
                    if (int.Parse(dt.Rows[i]["Room_ID"].ToString()) > max)
                    {
                        max = int.Parse(dt.Rows[i]["Room_ID"].ToString());
                    }
                }
                i = max + 1;
            }
            else
            {
                i = 0;
            }
            return "PC_00" + i;
        }

        #endregion

        #region[Search]

        protected void Search_Event(object sender, DirectEventArgs e)
        {
            DataTable dtRoom = clsRoom.Search(txtSearch.Text);
            if (dtRoom != null && dtRoom.Rows.Count > 0)
            {
                StoreRoom.DataSource = dtRoom;
                StoreRoom.DataBind();
            }
            else
            {
                grRoom.GetStore().RemoveAll();
            }
        }

        #endregion

        #region[Permisstion]
        private void CheckPermisstion()
        {
            if (Session["login"] != null && Session["USer_Detail_Id"].ToString() != string.Empty)
            {
                bool Is_BtnAdd;
                bool Is_BtnEdit;
                bool Is_BtnView;
                bool Is_BtnDel;
                bool Is_BtnPrint;
                bool Is_BtnCancel;
                bool Is_BtnReview;

                SecurityServices.HasPermisstion_Btn(StringContent.Room, out Is_BtnAdd, out Is_BtnEdit, out Is_BtnDel, out Is_BtnView, out Is_BtnCancel, out Is_BtnPrint, out Is_BtnReview);
                if (Is_BtnAdd == false)
                {
                    btnAddNew.Visible = false;
                }
                if (Is_BtnEdit == false)
                {
                    btnEdit.Visible = false;
                }
                if (Is_BtnView == false)
                {
                    PanelRoom.Visible = false;
                }
                if (Is_BtnDel == false)
                {
                    btnDel.Visible = false;
                }
                if (Is_BtnPrint == false)
                {
                    btnExport.Visible = false;
                }
            }
        }
        private bool CheckPermisstionDobclick()
        {
            var check = false;
            if (Session["login"] != null && Session["USer_Detail_Id"].ToString() != string.Empty)
            {
                bool Is_BtnAdd;
                bool Is_BtnEdit;
                bool Is_BtnView;
                bool Is_BtnDel;
                bool Is_BtnPrint;
                bool Is_BtnCancel;
                bool Is_BtnReview;

                SecurityServices.HasPermisstion_Btn(StringContent.Room, out Is_BtnAdd, out Is_BtnEdit, out Is_BtnDel, out Is_BtnView, out Is_BtnCancel, out Is_BtnPrint, out Is_BtnReview);
                if (Is_BtnEdit == false)
                {
                    check = true;
                }
            }
            return check;
        }
        #endregion
        //----------Button-Windows---------------
        private void WindowsUnit()
        {
            Window win = new Window()
            {
                ID = "WindowsUnit",
                Title = "Đơn vị tính",
                Width = 829,
                Height = 400,
                Modal = true,
                AutoRender = false,
                Collapsible = false,
                Maximizable = true,
                Hidden = true,
                Loader = new ComponentLoader
                {
                    Url = "../PageParrent/Unit.aspx",
                    Mode = LoadMode.Frame,
                    LoadMask =
                    {
                        ShowMask = true
                    }
                }
            };
            this.Controls.Add(win);
        }
        private void WindowsBranch()
        {
            Window win = new Window()
            {
                ID = "WindowsBranch",
                Title = "Chi nhánh",
                Width = 829,
                Height = 400,
                Modal = true,
                AutoRender = false,
                Collapsible = false,
                Maximizable = true,
                Hidden = true,
                Loader = new ComponentLoader
                {
                    Url = "../PageParrent/Branch.aspx",
                    Mode = LoadMode.Frame,
                    LoadMask =
                    {
                        ShowMask = true
                    }
                }
            };
            this.Controls.Add(win);
        }
        private void WindowsWarehouse()
        {
            Window win = new Window()
            {
                ID = "WindowsWarehouse",
                Title = "Kho",
                Width = 829,
                Height = 400,
                Modal = true,
                AutoRender = false,
                Collapsible = false,
                Maximizable = true,
                Hidden = true,
                Loader = new ComponentLoader
                {
                    Url = "../PageParrent/Warehouse.aspx",
                    Mode = LoadMode.Frame,
                    LoadMask =
                    {
                        ShowMask = true
                    }
                }
            };
            this.Controls.Add(win);
        }
    }
}